import os
import re
import sys
import json
import random
import requests
from os import path
from PIL import Image
import win32gui ,win32con, win32api

# Query Images
searchURL = 'https://unsplash.com/napi/search?client_id=%s&query=%s'
client_id = 'fa60305aa82e74134cabc7093ef54c8e2c370c47e73152f72371c828daedfcd7'
categories = ['simple', 'science', 'landscape']
randomSearch = random.choice(categories)
searchURL = searchURL % (client_id, randomSearch)
print(u'Searching \'%s\' from Unsplash...' % randomSearch)
response = requests.get(searchURL)
data = json.loads(response.text)
page = random.randint(1, data['photos']['total_pages'])
print(u'Total: %s, choose page %d' % (data['photos']['total'], page))
pageURL = searchURL + ('&page=%d' % page)
response = requests.get(pageURL)

# Parse Images
data = json.loads(response.text)
results = data['photos']['results']
results = list(filter(lambda x:float(x['width'])/x['height'] >=1.33,results))
result = random.choice(results)
resultId = str(result['id'])
resultURL = result['urls']['full']

# Download Images
print(u'Downloading:%s...' % resultId)
basePath = 'D:\\'
if(os.path.isfile(basePath)):
    basePath = os.path.dirname(basePath)
baseFolder = basePath + 'wallpapper\\'
if(not path.exists(baseFolder)):
    os.makedirs(baseFolder)
jpgFile = baseFolder + resultId + '.jpg'
response = requests.get(resultURL)
with open(jpgFile,'wb') as file:
    file.write(response.content)

print(u'Setting %s as wallpapper...' % resultId)
key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
    "Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2") 
#2拉伸适应桌面,0桌面居中
win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,jpgFile,win32con.SPIF_SENDWININICHANGE)
print(u'Succeed!')

key = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,
    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\PersonalizationCSP",0,win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(key, "LockScreenImagePath", 0, win32con.REG_SZ, jpgFile) 